package com.heng.groupchat.exception;

import com.heng.groupchat.common.BaseResponse;
import com.heng.groupchat.common.ResultUtils;
import com.heng.groupchat.common.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author faye
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 拦截并处理业务异常
     * @param e 业务异常
     * @return 响应类
     */
    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("businessException: " + e.getMessage(), e);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    /**
     * 拦截并处理参数校验异常
     * @param e 参数校验异常
     * @return 响应类
     */
    @ExceptionHandler(BindException.class)
    public BaseResponse<?> bindExceptionHandler(BindException e) {
        log.error("bindException", e);
        return ResultUtils.error(
                StatusCode.PARAMS_ERROR,
                e.getAllErrors().get(0).getDefaultMessage()
        );
    }

    /**
     * 拦截并处理运行时异常
     * @param e 运行时异常
     * @return 响应类
     */
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
        log.error("runtimeException", e);
        return ResultUtils.error(StatusCode.SYSTEM_ERROR, e.getMessage());
    }
}

